package com.example.administrator.olddoctor;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.Base.BaseFragment;
import com.example.Fragment.AttentionFragment;
import com.example.Fragment.DoctorFragment;
import com.example.Fragment.FindFragment;
import com.example.Fragment.PersonalFragment;
import com.example.Fragment.TrackFragment;
import com.example.Receiver.NetWorkReceiver;
import com.example.activity.PostMessageActivity;
import com.example.activity.SeekActivity;
import com.example.tools.IAppCallBack;

public class MainActivity extends AppCompatActivity implements IAppCallBack, View.OnClickListener {
    public static Context allThis;
    public Button mChannel1, mChannel2, mChannel3, mChannel4;

    private AttentionFragment attentionFragment;//关注
    private DoctorFragment doctorFragment;//首页老中医
    private PersonalFragment personalFragment;//我的
    private TrackFragment trackFragment;//追踪
    private FindFragment findFragment;//发现

    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    public static String curFragmentTag;
    private NetWorkReceiver receiver;

    PackageInfo packageInfo = null;

    ProgressDialog pd;

    static MainActivity MainActivity;

    Toolbar mToolbar;
    private TextView title;
   // private  TextView title_123;

    private FloatingActionButton pMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MainActivity = this;
        setContentView(R.layout.activity_main);

//        setActionBar(getResources().getDrawable(R.mipmap.personal_15), "姐是老中医", null, null,
//                null, null);
        initToolbar();
        //提交上了123
        //提交了10、19  123123123




        initView();
        fragmentManager = getSupportFragmentManager();
        // 开启一个Fragment事务
        fragmentTransaction = fragmentManager.beginTransaction();
        setCurrentFragment("1");
        PackageManager packageManager = getPackageManager();
        try {
            packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void initToolbar(){
        mToolbar = (Toolbar) findViewById(R.id.toolbar_main);
        title = (TextView) mToolbar.findViewById(R.id.toolbar_main_title);
        title.setText("姐是老中医");
//        mToolbar.setTitle("姐是老中医");
        mToolbar.setTitleTextColor(Color.WHITE);

        //ToolBar里面还可以包含子控件
        mToolbar.findViewById(R.id.toolbar_main_btnSearch).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent intent = new Intent(MainActivity.this,SeekActivity.class);
               startActivity(intent);
            }
        });

        //取代原本的actionbar
        setSupportActionBar(mToolbar);


    }

        private void initView() {
        allThis = this;

            pMessage= (FloatingActionButton) findViewById(R.id.floatbtn_main);
            pMessage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(MainActivity.this, PostMessageActivity.class));
                }
            });

        mChannel1 = (Button) findViewById(R.id.channel1);
        mChannel2 = (Button) findViewById(R.id.channel2);
        mChannel3 = (Button) findViewById(R.id.channel3);
        mChannel4 = (Button) findViewById(R.id.channel4);
        mChannel1.setOnClickListener(this);
        mChannel2.setOnClickListener(this);
        mChannel3.setOnClickListener(this);
        mChannel4.setOnClickListener(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        allThis = this;
    }

    @Override
    public void onSuccess(Object data, String sucText, String fucName) {
//        mPbar.dismiss();
        if ("PersonCenter".equals(fucName)) {
            personalFragment = (PersonalFragment) getFragment(curFragmentTag);
            personalFragment.onSuccess(data, sucText, fucName);
        }
    }

    @Override
    public void onFailure(String errCode, String errText, String fucName) {
//        mPbar.dismiss();
        if ("PersonCenter".equals(fucName)) {
            personalFragment = (PersonalFragment) getFragment(curFragmentTag);
            personalFragment.onSuccess(errCode, errText, fucName);
        }
    }

    @Override
    public void onRequestStart() {

    }

    @Override
    public void onClick(View view) {
        mChannel1.setCompoundDrawablesWithIntrinsicBounds(null, getResources()
                .getDrawable(R.mipmap.comui_tab_doctor), null, null);
        mChannel2.setCompoundDrawablesWithIntrinsicBounds(null, getResources()
                .getDrawable(R.mipmap.comui_tab_attent), null, null);
        mChannel3.setCompoundDrawablesWithIntrinsicBounds(null, getResources()
                .getDrawable(R.mipmap.comui_tab_track), null, null);
        mChannel4.setCompoundDrawablesWithIntrinsicBounds(null, getResources()
                .getDrawable(R.mipmap.comui_tab_person), null, null);
        switch (view.getId()) {
            case R.id.channel1:
                mChannel1.setCompoundDrawablesWithIntrinsicBounds(
                        null,
                        getResources().getDrawable(
                                R.mipmap.comui_tab_doctor_selected), null, null);
//                getActionBarTitle().setText("老中医");
//                setActionBar(getResources().getDrawable(R.mipmap.personal_15), "姐是老中医", null, null,
//                        getResources().getDrawable(R.mipmap.bottom_search), null);
                title.setText("姐是老中医");
//                mToolbar.setTitle("姐是老中医");
                mToolbar.setTitleTextColor(Color.WHITE);
                pMessage.setVisibility(View.VISIBLE);
                setTabSelection("1");
//                mChannel1.setClickable(false);
//                Handler handler = new Handler();
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        mChannel1.setClickable(true);
//                    }
//
//                }, 20000);

                break;
            case R.id.channel2:
                mChannel2.setCompoundDrawablesWithIntrinsicBounds(
                        null,
                        getResources().getDrawable(
                                R.mipmap.comui_tab_attent_select), null, null);
                setTabSelection("2");
//                setActionBar(null, null,"发现",null,null,null);
                title.setText("发现");
//                mToolbar.setTitle("发现");
                mToolbar.setTitleTextColor(Color.WHITE);
                pMessage.setVisibility(View.VISIBLE);
                break;
            case R.id.channel3:
                mChannel3.setCompoundDrawablesWithIntrinsicBounds(
                        null,
                        getResources().getDrawable(
                                R.mipmap.comui_tab_track_selected), null, null);
                setTabSelection("3");
//                setActionBar(null, null,"追姐",null,null,null);
                title.setText("追姐");
//                mToolbar.setTitle("追姐");
                mToolbar.setTitleTextColor(Color.WHITE);
                pMessage.setVisibility(View.GONE);
                break;
            case R.id.channel4:
                mChannel4.setCompoundDrawablesWithIntrinsicBounds(
                        null,
                        getResources().getDrawable(
                                R.mipmap.comui_tab_person_selected), null, null);
                setTabSelection("4");
//                getActionBarTitle().setText("我的");
//                setActionBar(null, null,"我的",null,null,null);
                title.setText("我的");
//                mToolbar.setTitle("我的");
                mToolbar.setTitleTextColor(Color.WHITE);
                pMessage.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    /**
     * 第一次启动时默认选中第一个tab
     */
    public void setCurrentFragment(String flag) {
        if (flag.equals("1")) {
            if (doctorFragment == null) {
                // 如果Fragment为空，则创建一个并添加到界面上
                mChannel1
                        .setCompoundDrawablesWithIntrinsicBounds(
                                null,
                                getResources().getDrawable(
                                        R.mipmap.comui_tab_doctor_selected),
                                null, null);
//                getActionBarTitle().setText("首页");
                doctorFragment = new DoctorFragment();
                fragmentTransaction.add(R.id.tabcontent, doctorFragment, "1");
                commitTransactions();
            }
        }
//        else if (flag.equals("2")) {
//            if (trackFragment == null) {
//                trackFragment = new TrackFragment();
//                fragmentTransaction.replace(R.id.tabcontent, trackFragment,
//                        "2");
//                commitTransactions();
//                mChannel1.setBackgroundColor(getResources().getColor(
//                        R.color.bottom_blue));
//                mChannel1.setCompoundDrawablesWithIntrinsicBounds(null,
//                        getResources().getDrawable(R.drawable.comui_tab_doctor),
//                        null, null);
//                mChannel3
//                        .setCompoundDrawablesWithIntrinsicBounds(
//                                null,
//                                getResources().getDrawable(
//                                        R.drawable.comui_tab_person), null,
//                                null);
//
//            }
//        }
        curFragmentTag = flag;

    }

    /**
     * 设置显示的fragment页面
     */
    public void setTabSelection(String tag) {
        if (tag.equals("1")) {
            if (doctorFragment == null) {
                doctorFragment = new DoctorFragment();
            }
        } else if (tag.equals("2")) {
            if (trackFragment == null) {
                trackFragment = new TrackFragment();
            }
        } else if (tag.equals("3")) {
            if (findFragment == null) {
                findFragment = new FindFragment();
            }
        } else if (tag.equals("4")) {
            if (personalFragment == null) {
                personalFragment = new PersonalFragment();
            }
        }
        if (TextUtils.equals(tag, curFragmentTag)) {
            return;
        }
        if (curFragmentTag != null) {
            detachFragment(getFragment(curFragmentTag));
        }
        attachFragment(R.id.tabcontent, getFragment(tag), tag);
        curFragmentTag = tag;
        commitTransactions();
    }


    private void detachFragment(Fragment f) {
        if (f != null && !f.isDetached()) {
            ensureTransaction();
            fragmentTransaction.detach(f);
        }
    }

    private FragmentTransaction ensureTransaction() {
        if (fragmentTransaction == null) {
            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        }
        return fragmentTransaction;
    }

    private void attachFragment(int layout, Fragment f, String tag) {
        if (f != null) {
            if (f.isDetached()) {
                ensureTransaction();
                fragmentTransaction.attach(f);
            } else if (!f.isAdded()) {
                ensureTransaction();
                fragmentTransaction.add(layout, f, tag);
            }
        }
    }

    private void commitTransactions() {
        if (fragmentTransaction != null && !fragmentTransaction.isEmpty()) {
            fragmentTransaction.commit();
            fragmentTransaction = null;
        }
    }

    private Fragment getFragment(String tag) {
        Fragment f = fragmentManager.findFragmentByTag(tag);
        if (f == null) {
            f = BaseFragment.newInstance(getApplicationContext(), tag);
        }
        return f;
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                exitTime = System.currentTimeMillis();
//                showToast("再按一次退出程序");
                Toast.makeText(this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
            } else {
                exitTime = 0;
                this.finish();
                this.onDestroy();
                System.exit(0);
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            super.openOptionsMenu();
        }
        return true;
    }



    // 取消注册方法
    private void unregisterReceiver() {
        // TODO Auto-generated method stub
        this.unregisterReceiver(receiver);
    }

    // 注册广播方法
    private void registerReceiver() {
        // TODO Auto-generated method stub
        IntentFilter intentFilter = new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetWorkReceiver();
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        // 取消注册
        unregisterReceiver();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // 注册广播
        registerReceiver();
    }
}
